<template>
    <el-menu
        :collapse="collapse" 
        :default-active="activeMenuId"
        router 
        class="menu">
        <template v-for="item in menuData">
            <el-menu-item v-if="item.route"
                :route="item.route"
                :index="item.id"
                :key="item.id">
<!--                <i :class="item.iconClass"></i>-->
                <!-- <img :src="imgSrc(item)" class="img-icon"> -->
                <template #title>{{ item.title }}</template>
            </el-menu-item>
            
            <el-sub-menu v-else
                :index="item.id"
                :key="item.id">
                <template #title>
                    <!-- <i class="menu-icon" :class="item.iconClass"></i> -->
                    <span>{{ item.title }}</span>
                </template>
                <el-menu-item v-for="subItem in item.children" 
                    :index="subItem.id"
                    :route="subItem.route"
                    :key="subItem.id">
                    <!-- <span class="menu-icon" :class="subItem.iconClass"></span> -->
                    <template #title>{{ subItem.title }}</template>
                </el-menu-item>
            </el-sub-menu>
        </template>
    </el-menu>
</template>

<script>
import { computed, watch } from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
import MenuData from './menu';

export default {
    name: 'Menu',
    props: ['collapse'],
    setup() {
        const store = useStore();
        const route = useRoute();

        // 用户菜单
        const menuData = computed(() => {
            return MenuData;
            // return store.getters['user/userMenus']
        });

        // 当前路径对应菜单
        // const currentMenu = computed(() => {
        //     return store.state.user.currentMenu
        // })

        // 高亮菜单
        const activeMenuId = computed(() => {
            return store.state.user.activeMenu.id
        })

        const imgSrc = (item) => {
            return require(`@/assets/img/menu/${item.iconClass}${activeMenuId.value == item.id ? '-active' : ''}.png`)
        }

        // 监听路径变化
        watch(() => route.path, () => {
            store.commit('user/setCurrentMenu', {
                currentName: route.name,
                activeMenuName: route.meta.activeMenuName,
                currentPage: {
                    url: route.path,
                    menuName: route.meta.title
                }
            })
        }, {
            immediate: true
        })

        // 无该菜单权限，则跳转首页【暂不可用】
        // watch(currentMenu, () => {
        //     if(!currentMenu.value.id) {
        //         router.replace({ path: '/welcome' })
        //     }
        // })

        return {
            menuData,
            // currentMenu,
            activeMenuId,
            imgSrc
        }
    }
}
</script>
